Python新手学习raise用法 | 您所在的位置:网站首页 › raise python › Python新手学习raise用法 |
一、平稳序列建模步骤 假如某个观察值序列通过序列预处理可以判定为平稳非白噪声序列,就可以利用ARMA模型对该序列进行建模。建模的基本步骤如下: (1)求出该观察值序列的样本自相关系数(ACF)和样本偏自相关系数(PACF)的值。 (2)根据样本自相关系数和偏自相关系数的性质,选择适当的ARMA(p,q)模型进行拟合。 (3)估计模型中位置参数的值。 (4)检验模型的有效性。如果模型不通过检验,转向步骤(2),重新选择模型再拟合。 (5)模型优化。如果拟合模型通过检验,仍然转向不走(2),充分考虑各种情况,建立多个拟合模型,从所有通过检验的拟合模型中选择最优模型。 (6)利用拟合模型,预测序列的将来走势。 二、代码实现 1、绘制时序图,查看数据的大概分布 trainSeting.head() Out[36]: date 2017-10-01 126.4 2017-10-02 82.4 2017-10-03 78.1 2017-10-04 51.1 2017-10-05 90.9 Name: sales, dtype: float64 plt.plot(trainSeting) 2、平稳性检验 '''进行ADF检验 adf_test的返回值 Test statistic:代表检验统计量 p-value:代表p值检验的概率 Lags used:使用的滞后k,autolag=AIC时会自动选择滞后 Number of Observations Used:样本数量 Critical Value(5%) : 显著性水平为5%的临界值。 (1)假设是存在单位根,即不平稳; (2)显著性水平,1%:严格拒绝原假设;5%:拒绝原假设,10%类推。 (3)看P值和显著性水平a的大小,p值越小,小于显著性水平的话,就拒绝原假设,认为序列是平稳的;大于的话,不能拒绝,认为是不平稳的 (4)看检验统计量和临界值,检验统计量小于临界值的话,就拒绝原假设,认为序列是平稳的;大于的话,不能拒绝,认为是不平稳的 ''' #滚动统计 def rolling_statistics(timeseries): #Determing rolling statistics rolmean = pd.rolling_mean(timeseries, window=12) rolstd = pd.rolling_std(timeseries, window=12)
#Plot rolling statistics: orig = plt.plot(timeseries, color='blue',label='Original') mean = plt.plot(rolmean, color='red', label='Rolling Mean') std = plt.plot(rolstd, color='black', label = 'Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.show(block=False)
##ADF检验 from statsmodels.tsa.stattools import adfuller def adf_test(timeseries): rolling_statistics(timeseries)#绘图 print ('Results of Augment Dickey-Fuller Test:') dftest = adfuller(timeseries, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used']) for key,value in dftest[4].items(): dfoutput['Critical Value (%s)'%key] = value #增加后面的显著性水平的临界值 print (dfoutput)
adf_test(trainSeting) #从结果中可以看到p值为0.1097>0.1,不能拒绝H0,认为该序列不是平稳序列 返回结果如下 Results of Augment Dickey-Fuller Test: Test Statistic -5.718539e+00 p-value 7.028398e-07 #Lags Used 0.000000e+00 Number of Observations Used 6.200000e+01 Critical Value (1%) -3.540523e+00 Critical Value (5%) -2.909427e+00 Critical Value (10%) -2.592314e+00 dtype: float64 通过上面可以看到,p值小于0.05,可以认为该序列为平稳时间序列。 3、白噪声检验 '''acorr_ljungbox(x, lags=None, boxpierce=False)函数检验无自相关 lags为延迟期数,如果为整数,则是包含在内的延迟期数,如果是一个列表或数组,那么所有时滞都包含在列表中最大的时滞中 boxpierce为True时表示除开返回LB统计量还会返回Box和Pierce的Q统计量 返回值: lbvalue:测试的统计量 pvalue:基于卡方分布的p统计量 bpvalue:((optionsal), float or array) – test statistic for Box-Pierce test bppvalue:((optional), float or array) – p-value based for Box-Pierce test on chi-square distribution ''' from statsmodels.stats.diagnostic import acorr_ljungbox def test_stochastic(ts,lag): p_value = acorr_ljungbox(ts, lags=lag) #lags可自定义 return p_value test_stochastic(trainSeting,[6,12]) Out[62]: (array([13.28395274, 14.89281684]), array([0.03874194, 0.24735042])) 从上面的分析结果中可以看到,延迟6阶的p值为0.03 |
CopyRight 2018-2019 实验室设备网 版权所有 |